package com.example.everying.service.pay.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.framework.pay.service.WechatTransferService;
import com.example.everying.mapper.pay.TransferBatchMapper;
import com.example.everying.model.dto.pay.*;
import com.example.everying.model.entity.pay.TransferBatchEntity;
import com.example.everying.model.entity.pay.notify.TransferNotifyEntity;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserBalanceTransactionEntity;
import com.example.everying.service.pay.TransferBatchService;
import com.example.everying.service.pay.TransferNotifyService;
import com.example.everying.service.user.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import com.example.everying.constant.OrderConstants;
import com.example.everying.context.UserContext;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.service.user.UserBalanceTransactionService;
import com.example.everying.utils.Result;
import com.example.everying.utils.WeChatUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TransferBatchServiceImpl extends ServiceImpl<TransferBatchMapper, TransferBatchEntity> implements TransferBatchService {

    @Autowired
    private WechatTransferService wechatTransferService;

    @Autowired
    private UserBalanceService userBalanceService;

    @Autowired
    private UserBalanceTransactionService userBalanceTransactionService;
    @Autowired
    private UserService userService;

    @Autowired
    private TransferNotifyService transferNotifyService;


    /**
     * 发起转账批次
     *
     * @param dto 转账批次实体
     * @return Result
     */
    @Transactional
    @Override
    public Result<?> createTransferBatch(TransferBatchEntityDto dto) {
        // 获取当前用户
        UserEntity user = UserContext.getUser();
        if (user == null) {
            return Result.fail("用户未登录");
        }

        if (user.getOpenId() == null) {
            return Result.fail("用户未绑定微信");
        }
        UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(user.getId());
        if (userBalance == null) {
            return Result.fail("用户余额不存在");
        }
        if (userBalance.getAvailableAmount().compareTo(new BigDecimal(dto.getAmt())) < 0) {
            return Result.fail("用户余额不足");
        }
        TransferBatchEntity batchEntity = new TransferBatchEntity();
        // 设置基础字段
        log.info("构建实体");
        String batchNo = WeChatUtil.generateOrderTradeNumber(OrderConstants.TRANSACTION_TYPE_PREFIX_WITHDRAW); // 生成批次号
        batchEntity.setChannelId(1); // 微信
        batchEntity.setBatchNo(batchNo);
        batchEntity.setUserId(user.getId());
        batchEntity.setOpenId(user.getOpenId());
        batchEntity.setCreateTime(LocalDateTime.now());
        batchEntity.setBatchStatus("PENDING"); // 初始状态：待处理
        batchEntity.setBatchType(OrderConstants.TRANSACTION_TYPE_WITHDRAW);
        batchEntity.setBatchRemark("提现");
        batchEntity.setTotalAmount(dto.getAmt());
        batchEntity.setTotalNum(1);

        boolean saved = this.save(batchEntity);
        log.info("保存批次信息：{}", batchEntity);
        if (!saved) {
            return Result.fail("创建转账批次失败");
        }
        String decs = user.getRealName() + "提现";
//        List<TransferDetailInput> transferDetails = new ArrayList<>();
//        TransferDetailInput transferDetailInput = new TransferDetailInput();
//        transferDetailInput.setOpenid(user.getOpenId());
//        // 微信支付用的分，这里金额要×100
//        transferDetailInput.setTransferAmount((long) dto.getAmt() * 100);  // 分账金额最大为10%
//        transferDetailInput.setTransferRemark("提现");
//        transferDetailInput.setUserName(user.getRealName());
//        transferDetailInput.setOutDetailNo(batchNo);
//        transferDetails.add(transferDetailInput);

//        InitiateBatchTransferResponse response = wechatTransferService.initiateTransfer(batchNo, decs, transferDetails);

        TransferToUserRequest request = new TransferToUserRequest();
        request.setTransferSceneId("1005"); // 佣金报酬
        request.setOutBillNo(batchNo);
        request.setTransferAmount((long) dto.getAmt() * 100);
        request.setUserName(user.getRealName());
        request.setOpenid(user.getOpenId());
        request.setTransferRemark(decs);
        List<TransferSceneReportInfo> TransferSceneReportInfos = new ArrayList<>();
        TransferSceneReportInfo item0 = new TransferSceneReportInfo();
        item0.setInfoType("岗位类型");
        item0.setInfoContent("提现奖励");
        TransferSceneReportInfos.add(item0);
        TransferSceneReportInfo item1 = new TransferSceneReportInfo();
        item1.setInfoType("报酬说明");
        item1.setInfoContent("提现奖励");
        TransferSceneReportInfos.add(item1);
        request.setTransferSceneReportInfos(TransferSceneReportInfos);


        log.info("发起微信提现接口:{}", request);
        TransferToUserResponse response2 = wechatTransferService.transfer(request);
        log.info("微信提现接口返回：{}", response2);
        if (response2 == null) {
            batchEntity.setBatchStatus("CLOSED");
            this.updateById(batchEntity);
            return Result.fail("网络故障，请稍后重试");
        }

        if (TransferBillStatus.WAIT_USER_CONFIRM.equals(response2.getState())) {
            // 扣除用户余额
            handleWithdrawSuccess(user, BigDecimal.valueOf(dto.getAmt()), batchNo, userBalance);
            return Result.ok(response2);
        }

        return Result.ok();
    }
    /**
     * 处理成功的转账
     */
    @Transactional
    public void handleSuccessfulTransfer(TransferBatchEntity batch, TransferToUserResponse response) {
        log.info("处理成功转账，批次号: {}", batch.getBatchNo());

        batch.setBatchStatus("SUCCESS");
        batch.setChannelBatchNo(response.getTransferBillNo());
        updateById(batch);

        log.info("用户{}提现成功", batch.getUserId());
    }
    /**
     * 处理失败的转账并回滚余额
     */
    @Transactional
    public void handleFailedTransfer(TransferBatchEntity batch) {
        log.info("处理失败转账，批次号: {}", batch.getBatchNo());

        // 更新批次状态
        batch.setBatchStatus("FAILED");
        updateById(batch);

        // 回滚用户余额
        UserEntity user = userService.getById(batch.getUserId());
        UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(user.getId());

        if (user != null && userBalance != null) {
            BigDecimal amount = new BigDecimal(batch.getTotalAmount());

            // 返还余额
            boolean isReturned = userBalanceService.addBalance(user.getId(), amount);
            if (isReturned) {
                // 记录返还交易记录
                UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
                transaction.setUserId(user.getId());
                transaction.setTxId(batch.getBatchNo() + "_refund");
                transaction.setChangeAmount(amount);
                transaction.setBalanceSnapshot(userBalance.getAvailableAmount().add(amount));
                transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
                transaction.setTxType(OrderConstants.TYPE_USER_INCOME);
                transaction.setRemark("提现失败返还");
                transaction.setUserType(OrderConstants.USER_TYPE_USER);
                transaction.setType(OrderConstants.ORDER_TYPE_RECEIVE);
                userBalanceTransactionService.save(transaction);

                log.info("用户{}提现失败，已返还余额{}元", user.getRealName(), amount);
            } else {
                log.error("返还用户余额失败，用户ID={},金额={}", user.getId(), amount);
            }
        }
    }
    /**
     * @param request
     * @return
     */
    @Override
    @Transactional
    public JSONObject transferCallback(HttpServletRequest request) throws IOException {
        log.info("微信转账回调接口");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "SUCCESS");
        Map<String, Object> objectMap = wechatTransferService.transferCallback(request);
//        {mch_id=1716972837, out_bill_no=WD202506062Z8HUD, transfer_bill_no=1330007726227892506060047717874758, transfer_amount=100.0, state=SUCCESS, openid=oJL2v7bebvy0yUuMyFMfEmER-EkY, create_time=2025-06-06T14:26:32+08:00, update_time=2025-06-06T14:26:35+08:00, mchid=1716972837}
//        Map<String, Object> objectMap = new HashMap<>();
//        log.info("微信转账回调接口返回：{}", objectMap);
//        objectMap.put("mch_id", "1716972837");
//        objectMap.put("out_bill_no", "WD202506062Z8HUD");
//        objectMap.put("transfer_bill_no", "1330007726227892506060047717874758");
//        objectMap.put("state", "SUCCESS");
//        objectMap.put("transfer_amount", "100.0");
//        objectMap.put("openid", "oJL2v7bebvy0yUuMyFMfEmER-EkY");
//        objectMap.put("create_time", "2025-06-06T14:26:32+08:00");
//        objectMap.put("update_time", "2025-06-06T14:26:35+08:00");
        if (objectMap == null) {
            log.error("微信转账回调接口返回为空");
            jsonObject.put("message", "微信转账回调接口返回为空");
            return jsonObject;
        }
        if (objectMap.get("mch_id") == null) {
            log.error("微信转账回调接口返回商户号不存在");
            jsonObject.put("message", "商户号不存在");
            return jsonObject;
        }
        // 开始记录回调
        log.info("开始记录回调,业务单号：{}", objectMap.get("out_bill_no"));
        QueryWrapper<TransferBatchEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_no", objectMap.get("out_bill_no"));
        TransferBatchEntity batchEntity = baseMapper.selectOne(queryWrapper);
        if (batchEntity == null) {
            log.error("微信转账回调接口返回商户号不存在");
            jsonObject.put("message", "商户号不存在");
            return jsonObject;
        }
        QueryWrapper<TransferNotifyEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("batch_id", batchEntity.getId());
        TransferNotifyEntity transferNotifyEntity = transferNotifyService.getOne((queryWrapper2));
        if (transferNotifyEntity == null) {
            transferNotifyEntity = new TransferNotifyEntity();
            transferNotifyEntity.setBatchId(batchEntity.getId());
            transferNotifyEntity.setChannelId(1);
            transferNotifyEntity.setNotifyId(objectMap.get("out_bill_no").toString());
            transferNotifyEntity.setResourceType("transfer");
            transferNotifyEntity.setEventType("success");
            transferNotifyEntity.setNotifyType("BATCH");
            transferNotifyEntity.setNotifyTime(LocalDateTime.now());
            transferNotifyEntity.setHandleStatus("WAIT");
            transferNotifyEntity.setNotifyData(JSON.toJSONString(objectMap)); // 替换 toString()
            transferNotifyService.save(transferNotifyEntity);
        } else {
            transferNotifyEntity.setNotifyData(JSON.toJSONString(objectMap));
            transferNotifyService.updateById(transferNotifyEntity);
        }

        String state = objectMap.get("state").toString();

        if (batchEntity.getBatchStatus().equals("SUCCESS")) {
            log.error("转账回调失败，该业务已经处理:{}", batchEntity.getBatchStatus());
            jsonObject.put("message", "该业务已经处理");
            return jsonObject;
        }
//        UserEntity user = userService.getById(batchEntity.getUserId());
        if (state.equals("SUCCESS")) {
            log.info("转账回调成功，更新批次状态");
            batchEntity.setBatchStatus("SUCCESS");
            batchEntity.setChannelBatchNo(objectMap.get("transfer_bill_no").toString());
            this.updateById(batchEntity);
            log.info("用户{}提现成功", batchEntity.getUserId());
        } else if (state.equals("FAILED")) {
            log.info("转账回调失败，更新批次状态");
            batchEntity.setBatchStatus("FAILED");
            this.updateById(batchEntity);

            // 如果需要，可以在这里处理失败后的其他逻辑
        }
//        if (state.equals("SUCCESS")) {
//            log.info("转账回调成功,开始扣费");
//
//            // 后续改成回调接口处理
//            batchEntity.setBatchStatus("SUCCESS");
//            // 更新批次信息
//            batchEntity.setChannelBatchNo(objectMap.get("transfer_bill_no").toString());
//            this.updateById(batchEntity);
////            UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(user.getId());
////            // 扣减余额
////            String transferAmountStr = objectMap.get("transfer_amount").toString(); // 获取字符串形式的金额
////            BigDecimal amount = new BigDecimal(transferAmountStr).round(MathContext.DECIMAL32); // 直接用 BigDecimal 构造
////            amount = amount.multiply(BigDecimal.valueOf(0.01)); // 转换为元
////            log.info("转账回调，用户ID={},金额={}", user.getId(), amount);
//            // 扣减余额
////            handleWithdrawSuccess(user, amount, objectMap.get("out_bill_no").toString(), userBalance);
////            boolean isDeducted = userBalanceService.deductBalance(user.getId(), amount);
////            if (!isDeducted) {
////                log.error("转账回调失败，扣减余额失败");
////            } else {
////                // 记录余额交易记录
////                UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
////                transaction.setUserId(user.getId());
////                transaction.setTxId(objectMap.get("out_bill_no").toString());
////                transaction.setChangeAmount(amount);  // 微信单位为分
////                transaction.setBalanceSnapshot(userBalance.getAvailableAmount().subtract(amount));
////                transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
////                transaction.setTxType(OrderConstants.TYPE_USER_WITHDRAW);
////                transaction.setRemark("用户提现");
////                transaction.setUserType(OrderConstants.USER_TYPE_USER);
////                transaction.setType(OrderConstants.ORDER_TYPE_WITHDRAW);
////                userBalanceTransactionService.save(transaction);
////                log.info("{}提现成功,提现了{}元", user.getRealName(), amount);
////            }
//        }
        jsonObject.put("message", "处理成功");
        return jsonObject;
    }
    // 确认一下用户有没有点击确认,要是没有就退款
    @Override
    @Transactional
    public void confirmTransfer(String batchNo) {
        log.info("开始确认转账,业务单号：{}", batchNo);
        UserEntity user =UserContext.getUser() ;
        QueryWrapper<TransferBatchEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_no", batchNo);
        TransferBatchEntity batchEntity = baseMapper.selectOne(queryWrapper);
        if (batchEntity == null) {
            log.error("微信转账回调接口返回商户号不存在");
            return;
        }
        if (!batchEntity.getUserId().equals(user.getId())) {
            log.error("用户没有权限确认转账");
            return;
        }
        // 开始退款
        handleFailedTransfer(batchEntity);
    }
    /**
     * 处理用户提现成功后的余额扣减和交易记录保存
     *
     * @param user        用户实体
     * @param amount      提现金额（元）
     * @param outBillNo   外部订单号
     * @param userBalance 用户余额实体
     */
    private void handleWithdrawSuccess(UserEntity user, BigDecimal amount, String outBillNo, UserBalanceEntity userBalance) {
        log.info("调用提现接口扣减余额，用户ID={},金额={}", user.getId(), amount);
        boolean isDeducted = userBalanceService.deductBalance(user.getId(), amount);
        if (!isDeducted) {
            log.error("提现接口，扣减余额失败");
        } else {
            // 记录余额交易记录
            UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
            transaction.setUserId(user.getId());
            transaction.setTxId(outBillNo);
            transaction.setChangeAmount(amount);
            transaction.setBalanceSnapshot(userBalance.getAvailableAmount().subtract(amount));
            transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
            transaction.setTxType(OrderConstants.TYPE_USER_WITHDRAW);
            transaction.setRemark("用户提现");
            transaction.setUserType(OrderConstants.USER_TYPE_USER);
            transaction.setType(OrderConstants.ORDER_TYPE_WITHDRAW);
            userBalanceTransactionService.save(transaction);
            log.info("{}提现成功,提现了{}元", user.getRealName(), amount);
        }
    }

    /**
     * @param request
     * {
     *   "mchId": "1716972837",
     *   "outBillNo": "WD202506062D2UEK",
     *   "transferBillNo": "1330007726227892506060002661725678",
     *   "transferAmount": 100.0,
     *   "state": "SUCCESS",
     *   "openid": "oJL2v7bebvy0yUuMyFMfEmER-EkY",
     * //   "createTime": "2025-06-06T11:20:41+08:00",
     * //   "updateTime": "2025-06-06T11:20:45+08:00",
     *   "mchid": "1716972837"
     * }
     * @return
     */
//    @Override
//    @Transactional
//    public JSONObject transferCallback(TransferCallbackResult request) throws IOException {
//        log.info("微信转账回调接口");
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("code","SUCCESS");
////        Map<String, Object> objectMap=  wechatTransferService.transferCallback(request);
////        log.info("微信转账回调接口返回：{}", objectMap);
////        TransferCallbackResult result = new TransferCallbackResult();
////        result.setOutBillNo(objectMap.get("out_bill_no").toString());
////        result.setTransferBillNo(objectMap.get("transfer_bill_no").toString());
////        result.setState(TransferBillStatus.valueOf(objectMap.get("state").toString()));
////        result.setTransferAmount(Long.valueOf(objectMap.get("transfer_amount").toString()));
//        String state =request.getState().toString();
//        QueryWrapper<TransferBatchEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("batch_no", request.getOutBillNo());
//        TransferBatchEntity batchEntity =baseMapper.selectOne(queryWrapper);
//        if (batchEntity == null) {
//            log.error("转账回调失败，批次单号不存在");
//            jsonObject.put("message","未找到该业务数据");
//            return jsonObject;
//        }
//        UserEntity user = userService.getById(batchEntity.getUserId());
//        if (state.equals("SUCCESS")) {
//            request.setTransferAmount(request.getTransferAmount());
//            request.setOpenid(request.getOpenid());
//            request.setMchId(request.getMchId());
//            // 后续改成回调接口处理
//            batchEntity.setBatchStatus("SUCCESS");
//            // 更新批次信息
//            batchEntity.setChannelBatchNo(request.getTransferBillNo());
////            batchEntity.setBatchStatus("PROCESSING");
//            this.updateById(batchEntity);
//            UserBalanceEntity userBalance = userBalanceService.getBalanceByUserId(user.getId());
//            // 扣减余额
//            BigDecimal amount = BigDecimal.valueOf(request.getTransferAmount()).multiply(BigDecimal.valueOf(0.01));
//            log.info("转账回调，用户ID={},金额={}", user.getId(), amount);
//            boolean isDeducted = userBalanceService.deductBalance(user.getId(), amount);
//            if (!isDeducted) {
//                log.error("转账回调失败，扣减余额失败");
//            } else {
//                // 记录余额交易记录
//                UserBalanceTransactionEntity transaction = new UserBalanceTransactionEntity();
//                transaction.setUserId(user.getId());
//                transaction.setTxId(request.getOutBillNo());
//                transaction.setChangeAmount(amount);  // 微信单位为分
//                transaction.setBalanceSnapshot(userBalance.getAvailableAmount().subtract(amount));
//                transaction.setTxStatus(OrderConstants.TX_STATUS_SUCCESS);
//                transaction.setTxType(OrderConstants.TYPE_USER_WITHDRAW);
//                transaction.setRemark("提现");
//                transaction.setUserType(OrderConstants.USER_TYPE_USER);
//                userBalanceTransactionService.save(transaction);
//                log.info("{}提现成功,提现了{}元", user.getRealName(), amount);
//            }
//
//        }
////        } else {
//////            request.setFailReason(objectMap.get("fail_reason").toString());
////        }
////        jsonObject.put("message","处理成功");
//        return jsonObject;
//    }

}
